package com.atguigu.gmall.payment.receiver;

import com.atguigu.gmall.common.constant.MqConst;
import com.atguigu.gmall.enums.model.PaymentStatus;
import com.atguigu.gmall.enums.model.PaymentType;
import com.atguigu.gmall.payment.model.PaymentInfo;
import com.atguigu.gmall.payment.service.AlipayService;
import com.atguigu.gmall.payment.service.PaymentInfoService;
import com.rabbitmq.client.Channel;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @author: atguigu
 * @create: 2023-03-15 11:47
 */
@Slf4j
@Component
public class PaymentReceiver {

    @Autowired
    private PaymentInfoService paymentInfoService;

    @Autowired
    private AlipayService alipayService;


    /**
     * 监听关闭订单消息,将本地交易记录进行关闭
     *
     * @param orderId
     * @param message
     * @param channel
     */
    @SneakyThrows
    @RabbitListener(bindings = @QueueBinding(
            exchange = @Exchange(MqConst.EXCHANGE_DIRECT_PAYMENT_CLOSE),
            value = @Queue(value = MqConst.QUEUE_PAYMENT_CLOSE, durable = "true"),
            key = {MqConst.ROUTING_PAYMENT_CLOSE}
    ))
    public void processCloseOrderMsg(Long orderId, Message message, Channel channel) {
        try {
            if (orderId != null) {
                log.info("[支付系统]监听关闭本地交易记录消息:{}", orderId);
                //修改本地交易记录状态
                PaymentInfo paymentInfo = paymentInfoService.getPaymentInfo(orderId, PaymentType.ALIPAY.name());
                if (paymentInfo != null && PaymentStatus.UNPAID.name().equals(paymentInfo.getPaymentStatus())) {
                    //将交易状态改为关闭
                    paymentInfo.setPaymentStatus(PaymentStatus.CLOSED.name());
                    paymentInfoService.updateById(paymentInfo);
                    //查询支付宝交易记录状态
                    Boolean flag = alipayService.checkPaymentSatus(orderId);
                    if (flag) {
                        //关闭支付宝交易
                        alipayService.closeAliPay(orderId);
                    }
                }
                channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            }
        } catch (IOException e) {
            log.error("[支付系统]监听关闭本地交易记录异常:", e);
            channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, true);
        }
    }
}
